package ar.com.maddes.creenciasadventistas.database;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import ar.com.maddes.creenciasadventistas.R;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String DB_NAME = "creencias.db";
	private static final String QUERY = "SELECT * FROM creencias c LEFT JOIN doctrinas d ON c.doctrina=d._ID WHERE c._ID=?";
	private static final String QUERY_DOCTRINA = "SELECT d.title FROM creencias c LEFT JOIN doctrinas d ON c.doctrina=d._ID WHERE c._ID=?";

	private static Context mContext;
	private static SQLiteDatabase database;

	private DatabaseHelper(Context context) throws SQLException {

		super(context, DB_NAME, null, 1);
		DatabaseHelper.mContext = context;
		DatabaseHelper.database = getWritableDatabase();
	}

	public static DatabaseHelper instanciate(Context context) {
		return new DatabaseHelper(context);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		// Create database
		db.execSQL("CREATE TABLE " + Creencia.TABLE_NAME + " ("
				+ Creencia.DOCTRINA + " NUMERIC, " + Creencia.DESCRIPTION
				+ " TEXT, " + Creencia.TITLE + " TEXT, " + BaseColumns._ID
				+ " INTEGER PRIMARY KEY)");

		// Insert data
		String[] querys = mContext.getResources().getStringArray(
				R.array.database_initialize_querys);
		for (String query : querys) {
			db.execSQL(query);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.v("UPGRADING", "UPGRADING NOTHING");
	}

	public static void closeDatabase() {
		if (database != null)
			database.close();
	}

	public void close() {
		closeDatabase();
	}

	public static Cursor query(String table, String[] columns, long id) {

		return database.query(table, columns, "_ID=?",
				new String[] { String.valueOf(id) }, null, null, null);
	}

	public static Cursor getCreencia(long id) {

		return database.rawQuery(QUERY, new String[] { String.valueOf(id) });
	}

	public static Cursor getTitles() {

		return database
				.query(Creencia.TABLE_NAME, new String[] { BaseColumns._ID,
						Creencia.TITLE }, null, null, null, null, null);
	}

	public static Cursor getDoctrina(long id) {

		return database.rawQuery(QUERY_DOCTRINA,
				new String[] { String.valueOf(id) });
	}
}
